<template>
  <div class="scanner-view">
    <el-card class="scanner-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <h2>产品扫码</h2>
            <el-date-picker
              v-model="selectedDate"
              type="date"
              placeholder="选择日期"
              :default-value="new Date()"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :shortcuts="dateShortcuts"
              :disabled-date="disabledDate"
              @change="handleDateChange"
            />
          </div>
          <div class="header-actions">
            <!-- 批次设置 -->
            <div class="batch-settings">
              <el-switch
                v-model="batchEnabled"
                active-text="批次模式"
                inactive-text=""
                @change="updateBatchSettings"
              />
              <el-input-number
                v-if="batchEnabled"
                v-model="batchSize"
                :min="1"
                :max="100"
                size="small"
                :disabled="!batchEnabled"
                placeholder="批次数量"
                @change="updateBatchSettings"
                style="width: 120px; margin-left: 10px;"
              />
            </div>
            <el-button type="primary" @click="focusFirstInput">
              <el-icon><Aim /></el-icon>
              开始扫码
            </el-button>
            <el-button 
              type="danger" 
              @click="handleDeleteSelected"
              :disabled="!selectedRows.length"
            >
              <el-icon><Delete /></el-icon>
              删除选中 ({{ selectedRows.length }})
            </el-button>
          </div>
        </div>
      </template>

      <div class="scanner-input-area">
        <div class="scanner-inputs">
          <el-input
            ref="scannerInput1"
            v-model="currentCode1"
            placeholder="请扫描第一个条码"
            :class="{ 'is-error': lastScanError, 'is-warning': isDuplicate }"
            @keydown.enter.prevent="handleFirstScan"
            @keyup.enter.prevent="handleFirstScan"
            clearable
            :prefix-icon="Platform"
          />
          <el-input
            ref="scannerInput2"
            v-model="currentCode2"
            placeholder="请扫描第二个条码"
            :class="{ 'is-error': lastScanError, 'is-warning': isDuplicate }"
            @keydown.enter.prevent="handleSecondScan"
            @keyup.enter.prevent="handleSecondScan"
            clearable
            :prefix-icon="Platform"
          />
        </div>
        
        <!-- 统一提示区域，根据优先级显示不同提示 -->
        <div class="message-container">
          <!-- 批次信息 -->
          <div v-if="batchEnabled && currentBatch" class="batch-info">
            <div class="batch-status">
              <span class="batch-label">当前批次:</span>
              <span class="batch-count">
                {{ currentBatch.currentCount }} / {{ currentBatch.totalCount }}
              </span>
              <el-progress 
                :percentage="batchPercentage" 
                :status="currentBatch.isCompleted ? 'success' : ''"
                :stroke-width="10"
                style="width: 200px; margin-left: 10px;"
              />
              
              <el-tag 
                v-if="currentBatch.keyCode" 
                type="info" 
                class="product-tag"
              >
                {{ currentBatch.keyCode }}
              </el-tag>
              
              <el-button 
                v-if="!currentBatch.isCompleted && currentBatch.currentCount > 0" 
                size="small" 
                @click="startNewBatch" 
                type="warning"
              >
                结束当前批次
              </el-button>
            </div>
          </div>

          <div class="scan-message-area">
            <!-- 成功提示优先级最高 -->
            <div v-if="lastScanSuccess" class="scan-message success-message-large">
              <el-icon><CircleCheck /></el-icon>
              <span>扫描成功：{{ lastScanSuccess }}</span>
            </div>
            
            <!-- 错误提示优先级次之 -->
            <div v-else-if="lastScanError" class="scan-message" :class="isDuplicate ? 'warning-message-large' : 'error-message-large'">
              <el-icon>
                <component :is="isDuplicate ? 'Warning' : 'CircleClose'" />
              </el-icon>
              <span>{{ lastScanError }}</span>
            </div>
            
            <!-- 一般提示优先级最低 -->
            <div v-else-if="scanMessage" class="scan-message" :class="messageClass">
              <span>{{ scanMessage }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="scan-records">
        <div class="table-container">
          <div v-if="scanStore.records.length === 0" class="no-records-message">
            <el-empty description="暂无扫描记录" />
            <div class="record-tips">请扫描条码添加记录</div>
          </div>
          <template v-else>
            <div v-if="filteredRecords.length === 0" class="no-records-message">
              <el-empty :description="`${selectedDate}没有扫描记录`" />
              <div class="record-tips">请选择其他日期或扫描新条码</div>
            </div>
            <el-table 
              v-else
              ref="tableRef"
              :data="paginatedRecords" 
              border 
              stripe
              :max-height="tableHeight"
              @selection-change="handleSelectionChange"
              :span-method="batchEnabled ? tableSpanMethod : null"
              row-class-name="tableRowClassName"
              v-loading="isTableLoading"
              element-loading-text="加载中..."
            >
              <el-table-column 
                type="selection" 
                width="55"
                fixed="left"
              />
              
              <el-table-column 
                label="扫描时间" 
                width="180" 
                fixed
                sortable
                :sort-orders="['descending']"
                :sort-method="(a, b) => new Date(b.scanTime).getTime() - new Date(a.scanTime).getTime()"
              >
                <template #default="{ row }">
                  {{ row.scanTime ? formatDate(row.scanTime) : '-' }}
                </template>
              </el-table-column>
              
              <el-table-column 
                v-if="batchEnabled"
                label="批次" 
                width="100"
              >
                <template #default="{ row }">
                  <el-tag v-if="row.batchId" size="small" type="info">
                    {{ formatBatchId(row.batchId) }}
                  </el-tag>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              
              <el-table-column 
                label="扫码信息" 
                min-width="150"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.scanCode || '-' }}
                </template>
              </el-table-column>

              <el-table-column 
                label="产品编码" 
                min-width="120"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ getProductCode(row.keyCode) }}
                </template>
              </el-table-column>
              
              <el-table-column 
                label="产品名称" 
                prop="productName" 
                min-width="200"
                show-overflow-tooltip
              />
              
              <el-table-column 
                label="关键代码" 
                prop="keyCode" 
                width="120"
              />
              
              <el-table-column 
                label="状态" 
                width="100" 
                fixed="right"
              >
                <template #default="{ row }">
                  <el-tag type="success" effect="dark">成功</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>

        <div v-if="filteredRecords.length > 0" class="table-footer-container">
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[20, 30, 40, 50]"
              :total="filteredRecords.length"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>

          <div class="table-footer">
            <span class="record-count">
              {{ selectedDate === today ? '今日' : selectedDate }} 扫描：
              <em>{{ filteredRecords.length }}</em> 条
              （成功：<em class="success">{{ filteredRecords.length }}</em> 条，
              失败：<em class="error">{{ failureCount }}</em> 条）
            </span>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Platform, Aim, Delete, Warning, CircleCheck, CircleClose } from '@element-plus/icons-vue'
import { useScanStore } from '../stores/scan'
import { useProductStore } from '../stores/product'
import dayjs from 'dayjs'
import type { ScanRecord, BatchInfo } from '../types'

const scanStore = useScanStore()
const productStore = useProductStore()
const scannerInput1 = ref<any>()
const scannerInput2 = ref<any>()
const currentCode1 = ref('')
const currentCode2 = ref('')
const lastScanError = ref('')
const lastScanSuccess = ref('')
const scanMessage = ref('')
const messageClass = ref('')
const failureCount = ref(0)
const selectedRows = ref<ScanRecord[]>([])
const tableRef = ref()

// 添加重复标记
const isDuplicate = ref(false)

const selectedDate = ref(dayjs().format('YYYY-MM-DD'))
const today = computed(() => dayjs().format('YYYY-MM-DD'))

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今天',
    value: () => {
      return new Date()
    }
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    }
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    }
  }
]

// 禁用未来
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

// 根据选择的日期过滤记录
const filteredRecords = computed(() => {
  // 使用forceUpdate作为依赖，确保每次更新都会重新计算
  const update = forceUpdate.value; 
  console.log('过滤记录，当前日期:', selectedDate.value, '记录总数:', scanStore.records.length, '强制更新:', update);
  
  if (scanStore.records.length === 0) {
    return [];
  }
  
  // 确保记录存在且日期格式正确
  const filtered = scanStore.records.filter((record: ScanRecord) => {
    // 确保记录有扫描时间
    if (!record.scanTime) {
      console.log('记录没有扫描时间:', record);
      return false;
    }
    
    try {
      // 使用dayjs将记录时间转换为日期字符串（YYYY-MM-DD格式）
      const recordDate = dayjs(new Date(record.scanTime)).format('YYYY-MM-DD');
      console.log(`比较日期: 记录=${recordDate}, 选择=${selectedDate.value}`);
      
      return recordDate === selectedDate.value;
    } catch (error) {
      console.error('日期格式错误:', record.scanTime, error);
      return false;
    }
  });
  
  console.log('过滤后的记录数:', filtered.length);
  return filtered;
})

// 处理日期变化
const handleDateChange = (date: string | null) => {
  console.log('日期变更事件触发, 原值:', selectedDate.value, '新值:', date);
  
  if (date) {
    selectedDate.value = date;
    // 手动强制更新，确保视图刷新
    nextTick(() => {
      forceUpdate.value++;
      console.log('日期变更后强制更新完成, 新的过滤记录数:', filteredRecords.value.length);
    });
  } else {
    // 如果日期被清空，使用今天的日期
    selectedDate.value = dayjs().format('YYYY-MM-DD');
    nextTick(() => {
      forceUpdate.value++;
    });
  }
}

const formatDate = (date: string) => {
  return dayjs(date).format('HH:mm:ss')
}

// 处理表格选择变化
const handleSelectionChange = (selection: ScanRecord[]) => {
  // 过滤掉分隔行
  selectedRows.value = selection.filter(row => !row.isBatchSeparator);
}

// 删除选中记录
const handleDeleteSelected = async () => {
  if (!selectedRows.value.length) return

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？此操作不可恢复。`,
      '警告',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 删除选中的记录
    const selectedIds = selectedRows.value.map(row => row.id)
    scanStore.deleteRecords(selectedIds)
    selectedRows.value = []
    ElMessage.success('删除成功')
  } catch {
    // 用户取消操作
  }
}

const handleFirstScan = () => {
  console.log('First scan triggered:', currentCode1.value)
  if (!currentCode1.value) {
    // 重置其他提示
    lastScanSuccess.value = ''
    lastScanError.value = ''
    isDuplicate.value = false
    
    // 设置当前提示
    scanMessage.value = '请输入第一个条码'
    messageClass.value = 'error-message-large'
    return
  }
  
  // 清除提示
  scanMessage.value = ''
  messageClass.value = ''
  
  // 设置第二步提示
  scanMessage.value = '请扫描第二个条码'
  messageClass.value = 'warning-message-large'
  
  // 自动跳转到第二个输入框
  nextTick(() => {
    scannerInput2.value?.focus()
  })
}

// 添加处理状态标记
const isProcessing = ref(false)

// 批次相关的变量
const batchEnabled = ref(scanStore.batchConfig.enabled)
const batchSize = ref(scanStore.batchConfig.batchSize)
const currentBatch = computed(() => scanStore.currentBatch)
const batchPercentage = computed(() => {
  if (!currentBatch.value) return 0
  return Math.min(
    Math.round((currentBatch.value.currentCount / currentBatch.value.totalCount) * 100),
    100
  )
})

// 强制更新组件的标志
const forceUpdate = ref(0)

// 更新批次设置
const updateBatchSettings = () => {
  scanStore.updateBatchConfig({
    enabled: batchEnabled.value,
    batchSize: batchSize.value
  })
  
  // 强制更新视图
  forceUpdate.value++
  
  // 立即刷新过滤后的记录和分页
  nextTick(() => {
    console.log('批次设置更新后，记录数:', filteredRecords.value.length)
  })
}

// 开始新批次
const startNewBatch = () => {
  scanStore.startNewBatch()
  ElMessage.success('已开始新批次')
}

// 表格单元格合并方法 - 用于按批次显示分隔线
const tableSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  // 安全检查：如果任何必要参数为空，直接返回正常的单元格
  if (!row || !column || typeof rowIndex !== 'number' || typeof columnIndex !== 'number') {
    return { rowspan: 1, colspan: 1 };
  }
  
  // 只对启用批次的情况处理
  if (!batchEnabled.value) {
    return { rowspan: 1, colspan: 1 };
  }
  
  // 处理分隔行
  if (row.isBatchSeparator) {
    // 对于空白分隔行，第一列合并为整行，其他列不显示
    if (columnIndex === 0) {
      return { rowspan: 1, colspan: 9 }; // 9是列数，根据实际情况调整
    } else {
      return { rowspan: 0, colspan: 0 }; // 其他列不显示
    }
  }
  
  // 正常行正常显示
  return { rowspan: 1, colspan: 1 };
}

// 修改扫描逻辑，添加批次处理
const handleSecondScan = async () => {
  console.log('Second scan triggered:', currentCode2.value)
  if (!currentCode2.value) {
    // 重置其他提示
    lastScanSuccess.value = ''
    lastScanError.value = ''
    isDuplicate.value = false
    
    // 设置当前提示
    scanMessage.value = '请输入第二个条码'
    messageClass.value = 'warning-message-large'
    return
  }

  // 防止重复提交
  if (isProcessing.value) {
    console.log('Processing in progress, skipping')
    return
  }
  isProcessing.value = true

  try {
    console.log('Starting validation')
    // 重置状态
    lastScanSuccess.value = ''
    lastScanError.value = ''
    isDuplicate.value = false
    scanMessage.value = ''
    messageClass.value = ''

    // 验证两次扫描是否匹配
    if (currentCode1.value !== currentCode2.value) {
      console.log('Codes do not match')
      lastScanError.value = '两次扫描的条码不匹配'
      isDuplicate.value = false
      playSound('error')
      isProcessing.value = false
      return
    }

    console.log('Codes match, proceeding with scan')
    // 使用第一个条码进行扫描
    const result = scanStore.scanProduct(currentCode1.value)
    
    // 播放声音反馈
    playSound(result.success ? 'success' : 'error')
    
    // 显示扫描结果
    if (result.success && result.record) {
      console.log('Scan successful:', result.record)
      lastScanSuccess.value = result.record.productName
      
      // 打印调试信息
      console.log('当前记录总数:', scanStore.records.length)
      console.log('当前日期过滤:', selectedDate.value)
      console.log('过滤后记录数:', filteredRecords.value.length)
      
      // 强制更新视图
      forceUpdate.value++
      
      // 延迟一下再强制刷新一次，确保视图更新
      setTimeout(() => {
        forceUpdate.value++
        console.log('二次强制更新，过滤后记录数:', filteredRecords.value.length)
        
        // 如果是今天的记录，确保当前页为第一页以显示最新记录
        if (selectedDate.value === today.value) {
          currentPage.value = 1
        }
      }, 100)
      
      // 处理批次完成提示
      if (result.batchInfo?.isCompleted) {
        ElMessage({
          message: `批次已完成！(${result.batchInfo.currentCount}/${result.batchInfo.totalCount})`,
          type: 'success',
          duration: 3000
        })
      }
    } else {
      console.log('Scan failed:', result.message)
      lastScanError.value = result.message || '未知错误'
      isDuplicate.value = Boolean(result.message?.includes('重复'))
      failureCount.value++
    }
  } catch (error) {
    console.error('Scan error:', error)
    // 播放错误声音
    playSound('error')
    if (error instanceof Error) {
      lastScanError.value = error.message
      isDuplicate.value = error.message.includes('重复')
    } else {
      lastScanError.value = '未知错误'
      isDuplicate.value = false
    }
    failureCount.value++
  } finally {
    // 延迟清空输入框并重新聚焦第一个输入框
    setTimeout(() => {
      currentCode1.value = ''
      currentCode2.value = ''
      nextTick(() => {
        focusFirstInput()
      })
      isProcessing.value = false
    }, 500) // 给用户一个短暂的时间看到结果
  }
}

const focusFirstInput = () => {
  scannerInput1.value?.focus()
}

// 自动聚焦输入框和预加载音效
onMounted(() => {
  // 预加载成功语音
  const successAudio = new Audio()
  successAudio.src = '/sounds/pass.mp3'
  successAudio.preload = 'auto'
  successAudio.load()
  
  // 预加载失败语音
  const errorAudio = new Audio()
  errorAudio.src = '/sounds/ng.mp3'
  errorAudio.preload = 'auto'
  errorAudio.load()
  
  // 聚焦到输入框
  focusFirstInput()
  
  // 在组件挂载后立即触发一次强制更新
  forceUpdate.value++
  
  // 添加调试信息
  console.log('组件挂载完成，当前记录总数:', scanStore.records.length)
  console.log('当前日期:', selectedDate.value)
  console.log('过滤后记录数:', filteredRecords.value.length)
  console.log('分页后记录数:', paginatedRecords.value.length)
  
  // 确保表格高度计算正确和添加事件监听
  calculateTableHeight()
  window.addEventListener('resize', calculateTableHeight)
  
  // 设置初始日期筛选
  selectedDate.value = dayjs().format('YYYY-MM-DD')
  console.log('初始日期设置为今天:', selectedDate.value)
})

// 监听全局按键，随时准备扫码
const handleKeyPress = (event: KeyboardEvent) => {
  // 如果不是在输入框中，自动聚焦到第一个输入框
  const activeElement = document.activeElement;
  const isInInput1 = activeElement === scannerInput1.value?.$el.querySelector('input');
  const isInInput2 = activeElement === scannerInput2.value?.$el.querySelector('input');
  
  // 不处理组合键
  if (event.ctrlKey || event.altKey || event.metaKey) return;
  
  // 如果已经在其中一个输入框中，不需要重新聚焦
  if (!isInInput1 && !isInInput2) {
    focusFirstInput();
  }
}

onMounted(() => {
  window.addEventListener('keypress', handleKeyPress)
})

// 添加分页相关的响应式变量
const currentPage = ref(1)
const pageSize = ref(20) // 减小默认每页数量，防止过多数据加载

// 添加表格加载状态变量
const isTableLoading = ref(false)

// 分页后的数据
const paginatedRecords = computed(() => {
  // 使用forceUpdate作为依赖，确保每次更新都会重新计算
  const update = forceUpdate.value;
  console.log('计算分页数据，当前页:', currentPage.value, '每页条数:', pageSize.value, '强制更新:', update);
  
  // 开始加载
  isTableLoading.value = true;
  
  // 先检查是否有记录
  if (filteredRecords.value.length === 0) {
    console.log('没有过滤后的记录');
    isTableLoading.value = false;
    return [];
  }

  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;

  // 对记录进行倒序排序
  const sortedRecords = [...filteredRecords.value].sort((a: ScanRecord, b: ScanRecord) => 
    new Date(b.scanTime).getTime() - new Date(a.scanTime).getTime()
  );
  
  console.log('排序后记录数:', sortedRecords.length);
  
  // 如果启用了批次模式，在不同批次之间插入空白分隔行
  let processedRecords = [...sortedRecords];
  
  if (batchEnabled.value) {
    processedRecords = [];
    let lastBatchId: string | undefined = undefined;
    
    // 处理每个排序后的记录
    sortedRecords.forEach(record => {
      // 如果当前记录有批次ID且与上一个批次ID不同，则插入一个分隔行
      if (record.batchId && lastBatchId !== undefined && record.batchId !== lastBatchId) {
        // 添加一个空白分隔行
        processedRecords.push({
          id: -Date.now() - Math.random(), // 使用负数ID确保唯一性
          productCode: '',
          productName: '',
          keyCode: '',
          scanCode: '',
          scanTime: '',
          isValid: true,
          batchId: '',
          isBatchSeparator: true // 标记为分隔行
        } as ScanRecord);
      }
      
      // 记录当前批次ID
      lastBatchId = record.batchId;
      
      // 添加正常记录
      processedRecords.push(record);
    });
  }
  
  // 应用分页
  const pagedRecords = processedRecords.slice(start, end);
  console.log('分页后记录数:', pagedRecords.length);
  
  // 完成加载
  nextTick(() => {
    isTableLoading.value = false;
  });
  
  return pagedRecords;
})

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  isTableLoading.value = true;
  
  // 添加延时释放加载状态
  nextTick(() => {
    setTimeout(() => {
      isTableLoading.value = false;
    }, 300);
  });
}

// 处理每页条变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
  isTableLoading.value = true;
  
  // 添加延时释放加载状态
  nextTick(() => {
    setTimeout(() => {
      isTableLoading.value = false;
    }, 300);
  });
}

// 监听日期变化，重置分页并强制刷新
watch(selectedDate, (newDate) => {
  console.log('selectedDate 监听触发，新日期:', newDate);
  currentPage.value = 1;
  
  // 延迟一下再强制刷新，确保更新完成
  nextTick(() => {
    forceUpdate.value++;
    console.log('日期变更强制更新，当前值:', forceUpdate.value);
  });
})

// 计算表格高度
const tableHeight = ref(400) // 默认高度

// 在组件挂载后计算表格高度
onMounted(() => {
  calculateTableHeight()
  window.addEventListener('resize', calculateTableHeight)
})

// 组件卸载前移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', calculateTableHeight)
  window.removeEventListener('keypress', handleKeyPress)
})

// 计算表格高度的方法
const calculateTableHeight = () => {
  // 获取视口高度
  const viewportHeight = window.innerHeight
  // 减去其他元素的高度
  const headerHeight = 64 // 头部高度
  const inputAreaHeight = 100 // 输入区域高度
  const footerHeight = 120 // 页脚高度（包含分页和统计信息）
  const padding = 40 // 页面内边距
  const cardPadding = 40 // 卡片内边距
  
  tableHeight.value = viewportHeight - headerHeight - inputAreaHeight - footerHeight - padding - cardPadding
}

// 根据关键代码获取产品编码
const getProductCode = (keyCode: string) => {
  const product = productStore.products.find(p => p.keyCode === keyCode)
  return product?.productCode || '-'
}

// 播放声音的辅助函数
const playSound = (type: 'success' | 'error') => {
  const audio = new Audio()
  audio.src = `/sounds/${type === 'success' ? 'pass' : 'ng'}.mp3`
  // 设置音量（0.0 到 1.0）
  audio.volume = 0.7 // 语音提示需要稍大的音量
  
  // 播放音效
  audio.play().catch(err => {
    console.error('播放声音失败:', err)
    // 如果播放失败，使用系统提示
    if (type === 'error') {
      ElMessage.error({
        message: '扫码失败',
        duration: 1000
      })
    } else {
      ElMessage.success({
        message: '扫码成功',
        duration: 1000
      })
    }
  })
}

// 表格行类名
const tableRowClassName = ({ row }: { row: ScanRecord }) => {
  // 安全检查
  if (!row) {
    return '';
  }
  
  // 返回批次分隔行的特殊样式
  if (row.isBatchSeparator) {
    return 'is-batch-separator';
  }
  
  // 普通行
  return '';
}

// 格式化批次ID
const formatBatchId = (batchId: string) => {
  if (!batchId) return '-';
  
  // 使用不同的方式提取批次ID，确保唯一性
  if (batchId.startsWith('BATCH-')) {
    const timestamp = batchId.substring(6);
    
    // 使用时间戳的后6位，确保每个批次显示不同
    const lastDigits = timestamp.substring(timestamp.length - 6);
    // 添加分隔符，使其更易读
    return lastDigits.substring(0, 3) + '-' + lastDigits.substring(3);
  }
  
  // 对于其他格式的ID，使用后6位
  if (batchId.length > 6) {
    return batchId.substring(batchId.length - 6);
  }
  
  return batchId;
}
</script>

<style scoped>
.scanner-view {
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.scanner-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 重要：防止内容溢出 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.scanner-input-area {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: flex-start;
  gap: 20px;
  margin-bottom: 20px;
  max-width: 100%;
}

.is-error {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px var(--el-color-danger) inset;
  }
}

.is-warning {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px var(--el-color-warning) inset !important;
  }
}

.message {
  font-size: 14px;
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.error-message {
  composes: message;
  color: var(--el-color-danger);
}

.warning-message {
  composes: message;
  color: var(--el-color-warning);
}

.success-message {
  composes: message;
  color: var(--el-color-success);
}

.scan-records {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 重要：防止内容溢出 */
  min-height: 0; /* 要：允许flex子元素缩 */
}

.table-container {
  flex: 1;
  overflow: hidden; /* 重要：防止内容溢出 */
  position: relative;
  min-height: 0; /* 重要：允许flex子元素收缩 */
  background-color: #ffffff; /* 添加白色背景 */
}

:deep(.el-table) {
  height: 100%; /* 让表格填满容器 */
  background-color: #ffffff; /* 表格白色背景 */
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto !important; /* 强制显示垂直滚动条 */
}

.table-footer-container {
  flex-shrink: 0;
  background-color: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 12px;
  margin-top: auto; /* 将页脚推到底部 */
}

.pagination-container {
  padding: 0 20px;
  margin-bottom: 12px;
  display: flex;
  justify-content: flex-end;
}

.table-footer {
  padding: 12px 20px;
  background-color: var(--el-bg-color-page);
  border-radius: 0 0 4px 4px;
}

/* 确保表格内容垂直居中 */
:deep(.el-table__cell) {
  vertical-align: middle;
}

/* 优化滚动条样式 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px; /* 稍微加宽滚动条 */
  height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: var(--el-border-color-darker);
  border-radius: 4px;
  border: 2px solid transparent;
  background-clip: padding-box;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: var(--el-border-color-light);
  border-radius: 4px;
}

/* 确保固定列的阴影效果正确 */
:deep(.el-table__fixed-right) {
  height: 100% !important;
  bottom: 0 !important;
}

:deep(.el-table__fixed-left) {
  height: 100% !important;
  bottom: 0 !important;
}

/* 禁用状态的按钮样式 */
.el-button.is-disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;

  h2 {
    margin: 0;
    white-space: nowrap;
  }
}

:deep(.el-date-editor) {
  width: 200px;
}

.scanner-inputs {
  display: flex;
  flex-direction: column;
  gap: 16px;
  flex: 0 0 auto; /* 修改为固定宽度 */
  width: 400px; /* 设置固定宽度 */
}

.message-container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  min-height: 92px; /* 调整为两个输入框的总高度 */
  flex: 1; /* 占据剩余空间 */
  margin-left: 0; /* 移除左边距 */
}

.batch-info {
  background-color: var(--el-color-info-light-9);
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  width: 100%;
}

.scan-message-area {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  min-height: 50px; /* 调整高度 */
  flex: 1; /* 占据剩余空间 */
  margin-left: 0; /* 移除左边距 */
}

.scan-message {
  font-size: 32px; /* 稍微减小字体大小 */
  font-weight: bold;
  padding: 10px 20px;
  border-radius: 4px;
  white-space: nowrap; /* 防止文字换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  text-align: left; /* 文本左对齐 */
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: flex-start; /* 内容左对齐 */
  gap: 10px;
  margin-left: 0; /* 移除左边距 */
  max-width: 100%; /* 确保不会超出容器 */
}

.scan-message .el-icon {
  font-size: 28px; /* 稍微减小图标大小 */
  flex-shrink: 0; /* 防止图标缩小 */
}

.scan-message span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.error-message-large {
  color: var(--el-color-danger);
  background-color: var(--el-color-danger-light-9);
}

.warning-message-large {
  color: var(--el-color-warning);
  background-color: var(--el-color-warning-light-9);
}

.success-message-large {
  color: var(--el-color-success);
  background-color: var(--el-color-success-light-9);
}

/* 批次相关样式 */
.batch-settings {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 16px;
  border-right: 1px solid var(--el-border-color-light);
}

.batch-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.batch-label {
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.batch-count {
  font-weight: bold;
  color: var(--el-color-primary);
  min-width: 50px;
}

.product-tag {
  margin-left: 10px;
}

/* 批次分隔样式 */
:deep(.batch-separator) {
  border-top: 2px dashed var(--el-color-info-light-5) !important;
}

:deep(.el-progress) {
  margin-bottom: 0;
}

/* 批次空白行样式 */
:deep(.el-table__row.is-batch-separator) {
  background-color: var(--el-fill-color-lighter) !important;
  height: 6px !important;
}

:deep(.el-table__row.is-batch-separator td) {
  padding: 0 !important;
  border: none !important;
}

:deep(.el-table__row.is-batch-separator:hover td) {
  background-color: var(--el-fill-color-lighter) !important;
}

:deep(.el-table__row) {
  background-color: #ffffff !important; /* 表格行白色背景 */
}

:deep(.el-table__row.el-table__row--striped) {
  background-color: #fafafa !important; /* 条纹行浅灰背景 */
}

.no-records-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.record-tips {
  margin-top: 20px;
  color: var(--el-text-color-secondary);
}
</style> 